<?php
require_once('inc'.DIRECTORY_SEPARATOR.'ConfFile.php');

class CronFile extends ConfFile
{

  protected $CronTab = array();

  public function __construct($filename='n/a')
  {
    if ($filename=='n/a') $filename = 'cron.php';
    parent::__construct($filename);
    $this->Load();
    $this->CronTabCreate();
  }

  public function Timer($StartTime = 'n/a')
  {
    $return = array();
    if ($StartTime === 'n/a') $StartTime = time();
    for($Time = $StartTime;$Time <= time();$Time++)
    {
      $Times = explode(' ',date('s i H j n Y w', $Time));
      foreach ($this->CronTab as $Event){
        $Run = false;
        if (isset($Event['time'])) foreach($Event['time'] as $CronTimes)
        {
          $fulfilled = true;
          for ($i = 6;$fulfilled && ($i >= 0);$i--)
          {
            if ($CronTimes['lasttime'][$i] != $Times[$i])
            {
              $CronTimes['lastbool'][$i] = $this->Check($CronTimes['crontab'][$i],$Times[$i]);
              if (($i == 0) && $CronTimes['lastbool'][$i]) $Run = true;
            }
            if (!$CronTimes['lastbool'][$i]) $fulfilled = false;
          }
        }

        if ($Run) {
          $tmp['time'] = $Time;
          $tmp['file'] = $Event['file'];
          $tmp['part'] = $Event['part'];
          $tmp['data'] = $Event['data'];
          $return[] = $tmp;
          $tmp = array();
        }
      }
    }
    if (count($return) > 0) return $return;
    else return false;
  }

  protected  function Check($pattern, $time)
  {
    $pattern = explode(',',$pattern);
    foreach ($pattern as $patt)
    {
      if (ereg('^\*$',$patt)) return true;
      elseif (ereg('^[0-9]+$',$patt))
      {
        if ($patt == $time) return true;
      }
      elseif (ereg('^[0-9]+-[0-9]+$',$patt))
      {
        $tmp = array();
        $tmp = explode('-',$patt);
        if (($tmp[0] <= $time) AND ($tmp[1] >= $time)) return true;
      }
      elseif (ereg('\*/[0-9]+$',$patt))
      {
        $tmp = array();
        $tmp = explode('/',$patt);
        if (($time % $tmp[1]) == 0)  return true;
      }
    }
  }


  /**
   * Z pole Data vytvori CronTab.
   * Rozparsuje casy ulozene v jako text, porovna ho z casem zadanym jako parametr, pripadne s aktualnim casem a vysledky ulozi.
   *
   * @param integer $StartTime
   */
  protected function CronTabCreate($StartTime = 'n/a')
  {
    if ($StartTime === 'n/a') $StartTime = time();
    $Time = explode(' ',date('s i H j n Y w', $StartTime));
    $this->CronTab = array();
    foreach($this->Data as &$CronData)
    {
      //print_r($CronData);
      $tmp = array();
      foreach($CronData['cron'] as $nr => $CronTimes)
      {
        $CronTime = explode(' ',$CronTimes);
        $tmp['time'][$nr]['lasttime'] = $Time;
        $tmp['time'][$nr]['crontab']= $CronTime;
        for ($i = 6;$i >= 0;$i--)
        {
          $tmp['time'][$nr]['lastbool'][$i] = $this->Check($CronTime[$i] ,$Time[$i]);
        }
      }
      if (isset($CronData['file'][0])) $tmp['file'] = $CronData['file'][0];
      if (isset($CronData['part'][0])) $tmp['part'] = $CronData['part'][0];
      if (isset($CronData['data'])){
        $tmp['data'] = array();
        foreach($CronData['data'] as $Data)
        {
          eregi("([^=]+)=(.+)", $Data, $part);
          $tmp['data'][$part[1]] = $part[2];
        }
      }
      $this->CronTab[] = $tmp;
    }
  }

  public function Add($Time,$File,$Part = 'n/a',$Data = 'n/a',$Block = 'n/a')
  {
    // generovani nazvu bloku
    if ($Block === 'n/a'){
      $Block = time();
    }
    while (isset($this->Data[$Block])) $Block += rand();
    // kontrola jestli soubor existuje
    if (!file_exists('events'.DIRECTORY_SEPARATOR.$File))
    {
      $GLOBALS['Log']->Debug('file '.$File.' don\'nt exist!');
      return false;
    }
    // nastaveni a kontrola casu
    if (!is_array($Time)){
      if (is_numeric($Time)){
        $Time = explode(' ',date('s i H j n Y w', $Time));
      }
    }
    if (count($Time) != 7) {
      $GLOBALS['Log']->Debug('Time is in wrong format');
      return false;
    }
    // ulozeni do souboru
    $this->AddBlock($Block);
    $this->AddItem($Block,'file',$File);

    $Times = $Time[0];
    for ($i = 1;$i < 7;$i++) $Times .= ' '.$Time[$i];
    $this->AddItem($Block,'cron',$Times);

    if ($Part != 'n/a') $this->AddItem($Block,'part',$Part);
    if ($Data != 'n/a'){
      print_r($Data);
      foreach ($Data as $key => $value){
        $this->AddItem($Block,'data',$key.'='.$value);
        echo 'pridavam data: ',$key.'='.$value."\n";
      }
    }
    $this->CronTabCreate();
    //     if ($Part === 'n/a') unset($Part);

  }

}
?>